package com.vcs.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import com.vcs.domain.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileDownloadAction extends ActionSupport implements SessionAware {

	public static final Log log = LogFactory.getLog(FileDownloadAction.class);
	private InputStream fileInputStream;
	private String inputPath;
	Map<String, Object> sessionMap;

	public void setInputPath(String value) {
		inputPath = value;
	}

	public InputStream getInputStream() throws Exception {
		// return
		// ServletActionContext.getServletContext().getResourceAsStream(inputPath);
		return fileInputStream;

	}

	public String execute() throws Exception {

		// 1 Get Resume name from session
		String resumeName = ((Jobseeker) sessionMap.get("js")).getResumeName();

		log.info("Resume name obtained from session [" + resumeName + "]");

		ServletActionContext.getResponse().setHeader("Content-Disposition",
				"attachment; filename=\"" + resumeName + "\"");

		// String filepath =
		// ServletActionContext.getServletContext().getRealPath("\\downloads\\"
		// + resumeName);
		String opSys = System.getProperty("os.name"); // find OS
		log.info("Operating system is: [" + opSys + "]");

		String fullFileName = null;
		String workingDir = "downloads";

		if (opSys.equalsIgnoreCase("Linux")) {

			fullFileName = "." + File.separator + workingDir + File.separator
					+ resumeName;
		} else {
			fullFileName = File.separator + workingDir + File.separator
					+ resumeName;
		}

		// String filepath = "\\downloads\\" + resumeName;
		log.info("Full file path: [" + fullFileName + "]");
		try {
			fileInputStream = new FileInputStream(new File(fullFileName));
		} catch (FileNotFoundException fnf) {
			log.info("-----------Resume File Not Found ------------");
		}
		
		return SUCCESS;
	}

	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;

	}
}
